package vn.com.vtv.weather;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;

import org.apache.http.HttpResponse;
import org.apache.http.HttpVersion;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.ResponseHandler;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.conn.ClientConnectionManager;
import org.apache.http.conn.params.ConnManagerPNames;
import org.apache.http.conn.params.ConnPerRouteBean;
import org.apache.http.conn.scheme.PlainSocketFactory;
import org.apache.http.conn.scheme.Scheme;
import org.apache.http.conn.scheme.SchemeRegistry;
import org.apache.http.impl.client.BasicResponseHandler;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.impl.conn.SingleClientConnManager;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpParams;
import org.apache.http.params.HttpProtocolParams;

import vn.com.hoasua.database.smng.LinkMng;
import vn.com.hoasua.database.sobject.LinkPost;
import android.content.Context;

public class NetworkAdapter {
	Context context;

	public NetworkAdapter(Context context) {
		this.context = context;
	}

	public void sendHttpGet(final String url,
			final ArrayList<NameValuePair> param, final NetworkResponse handle) {

		new Thread(new Runnable() {

			@Override
			public void run() {
				String json = "";
				HttpClient client = new DefaultHttpClient();
				try {
					// Create Request to server and get response
					HttpGet httpget = new HttpGet(makeGetUrl(url, param));
					ResponseHandler<String> responseHandler = new BasicResponseHandler();
					json = client.execute(httpget, responseHandler);
					if (handle != null)
						handle.onSuccess(url, param, json);
				} catch (Exception ex) {
					ex.printStackTrace();
					if (handle != null)
						handle.onFailed(url, param, ex.getMessage());
				}
			}
		}).start();
	}

	public void sendHttpPost(final String url,
			final ArrayList<NameValuePair> param, final NetworkResponse handle) {
		HttpPost httppost = new HttpPost(url);
		HttpClient httpclient = new DefaultHttpClient();
		String restFulUrl = makeGetUrl(url, param);
		try {
			httppost.setEntity(new UrlEncodedFormEntity(param));
			HttpResponse response = httpclient.execute(httppost);
			String json = inputStreamToString(response.getEntity().getContent());

			// insert/update to database
			LinkMng mng = new LinkMng(context);
			ArrayList<LinkPost> lstJson = mng.select(LinkMng.link, restFulUrl);
			LinkPost link = new LinkPost(-1, restFulUrl, json,
					System.currentTimeMillis() + "");
			if (lstJson != null && !lstJson.isEmpty()) {
				mng.edit(lstJson.get(0)._id, link.getValues() + "");
			} else {
				mng.insertNewTo(link.getValues());
			}
			if (handle != null)
				handle.onSuccess(url, param, json);
			return;
		} catch (ClientProtocolException e) {
			e.printStackTrace();
			handle.onFailed(url, param, e.getMessage());
		} catch (IOException e) {
			e.printStackTrace();
			handle.onFailed(url, param, e.getMessage());
		} catch (Exception e) {
			e.printStackTrace();
			handle.onFailed(url, param, e.getMessage());
		}
	}

	public String makeGetUrl(String url, ArrayList<NameValuePair> params) {
		String strPrms = "?";
		for (NameValuePair param : params) {
			String get = param.getName() + "=" + param.getValue();
			strPrms = strPrms + get + "&";
		}
		return url + strPrms;
	}

	protected String inputStreamToString(InputStream is) {

		String line = "";
		StringBuilder total = new StringBuilder();

		// Wrap a BufferedReader around the InputStream
		BufferedReader rd = new BufferedReader(new InputStreamReader(is));

		try {
			// Read response until the end
			while ((line = rd.readLine()) != null) {
				total.append(line);
			}
		} catch (IOException e) {
			// Log.e(TAG, e.getLocalizedMessage(), e);
		}

		// Return full string
		return total.toString();
	}

	public DefaultHttpClient getHttpClient() {
		SchemeRegistry schemeRegistry = new SchemeRegistry();
		schemeRegistry.register(new Scheme("http", PlainSocketFactory
				.getSocketFactory(), 80));
		// schemeRegistry.register(new Scheme("https", new
		// EasySSLSocketFactory(), 443));
		HttpParams mHttpParams = null;
		;
		if (null == mHttpParams) {
			mHttpParams = new BasicHttpParams();
			mHttpParams.setParameter(ConnManagerPNames.MAX_TOTAL_CONNECTIONS,
					30);
			mHttpParams.setParameter(
					ConnManagerPNames.MAX_CONNECTIONS_PER_ROUTE,
					new ConnPerRouteBean(30));
			mHttpParams.setParameter(HttpProtocolParams.USE_EXPECT_CONTINUE,
					false);
			HttpProtocolParams.setVersion(mHttpParams, HttpVersion.HTTP_1_1);
			HttpConnectionParams.setConnectionTimeout(mHttpParams, 5000); // agent
																			// setting
			// 추가
			HttpConnectionParams.setSoTimeout(mHttpParams, 5000); //
		}
		ClientConnectionManager cm = new SingleClientConnManager(mHttpParams,
				schemeRegistry);
		DefaultHttpClient client = new DefaultHttpClient(cm, mHttpParams);
		return client;
	}

	public interface NetworkResponse {

		/**
		 * @return true: processed. false: not process
		 * */
		public void onSuccess(String url, ArrayList<NameValuePair> param,
				String json);

		/**
		 * @return true: processed. false: not process
		 * */
		public void onFailed(String url, ArrayList<NameValuePair> param,
				String json);
	}
}
